﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using GdHotel.Data;
using GdHotel.Data.Repositories;
using GdHotel.Web.Controllers;

namespace UniqueTechnologies.Attributes
{
    public class LanguageSupportAttribute : ActionFilterAttribute
    {
        private static Language GetLanguageByParam(String param, BaseController controller) 
        {
            param = param.ToLower();
            var language = controller.LanguagesRepository.GetByShortName(param);
            if (language == null)
                return controller.LanguagesRepository.GetDefault();
            return language;
        }

        private CultureInfo GetCultureByLanguage(Language language)
        {
            return new CultureInfo(language.CultureKey);
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var controller = (BaseController)filterContext.Controller;
            var controllerContext = controller.ControllerContext;
            if (!controllerContext.RouteData.Values.ContainsKey("lang"))
                return;

            var lang = controllerContext.RouteData.GetRequiredString("lang");
            var language = GetLanguageByParam(lang, controller);

            var ci = GetCultureByLanguage(language);
            Thread.CurrentThread.CurrentCulture = ci;
            Thread.CurrentThread.CurrentUICulture = ci;

            controller.Language = language;
            controller.ViewData["Language"] = language;
        }
    }
}